package com.overlord.im.connector.netty.handler;

import com.overlord.im.connector.netty.connector.ConnectorContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wuwei
 * @className HeartBeatHandler
 * @description
 * @date 2020-05-30 15:18
 **/
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private int lostConnection = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.info("接收到客户端心跳请求...");
                lostConnection++;
                if (lostConnection > 2) {
                    log.info("连接超过2个周期未写入信息，将断开连接");
                    ctx.channel().close();
                    log.info("清理ConnectorContext");
                    ConnectorContext.remove(ctx);
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        lostConnection = 0;
        super.channelRead(ctx, msg);
    }
}
